extends CanvasLayer

@export_group("初始状态配置")
@export var start_hidden: bool = true  #默认是 true
@onready var buttons_container: HBoxContainer = $DrinkMenuSystem/ButtonsContainer
@onready var btn_handle = $Btn_Handle
@onready var drink_menu_system = $DrinkMenuSystem
@onready var menu_content = $DrinkMenuSystem/MenuContent
@onready var btn_left = $DrinkMenuSystem/ButtonsContainer/Btn_Left
@onready var btn_close = $DrinkMenuSystem/ButtonsContainer/Btn_Close
@onready var btn_right = $DrinkMenuSystem/ButtonsContainer/Btn_Right
@export_group("酒单动画配置")
@export var open_offset: Vector2 = Vector2(-518, 0) 
@export var anim_duration: float = 0.6

@onready var settings_panel = $SettingsPanel
@onready var save_load_panel = $SaveLoadPanel
@onready var slot_list_container = $SaveLoadPanel/SlotContainer/SlotList
@onready var title_label = $SaveLoadPanel/TitleLabel
@onready var fullscreen_btn = $SettingsPanel/FullscreenRow/Btn_Fullscreen
@onready var volume_slider = $SettingsPanel/VolumeSlider
@onready var sfx_phone_open = $SFX_Phone_Open
@onready var sfx_phone_close = $SFX_Phone_Close
@onready var sfx_save: AudioStreamPlayer2D = $SFX_Special_Save
@onready var sfx_load: AudioStreamPlayer2D = $SFX_Special_Load

#音频总线索引
var master_bus_index = AudioServer.get_bus_index("Master")

#标记当前打开的是存档界面还是读档界面
var is_save_mode: bool = true
var pending_load_slot: String = ""
#酒单图片路径数组
var menu_pages: Array[String] = [
	"res://sprite/Background/phone_contant2.png",
	"res://sprite/Background/phone_contant3.png" 
]


var current_page: int = 0
var menu_tween: Tween

#位置记录
var pos_hidden_x: float
var pos_shown_x: float

var pos_closed: Vector2
var pos_opened: Vector2


func _ready():
	#连接 HUD 按钮信号
	$HUD/ButtonContainer/Btn_Settings.pressed.connect(_on_open_settings)
	$HUD/ButtonContainer/Btn_Save.pressed.connect(func(): _on_open_save_load(true)) # true 代表存档
	$HUD/ButtonContainer/Btn_Load.pressed.connect(func(): _on_open_save_load(false)) # false 代表读档
	
	#连接面板内部关闭按钮
	$SettingsPanel/Btn_CloseSettings.pressed.connect(_close_all_menus)
	$SaveLoadPanel/Btn_CloseSaveLoad.pressed.connect(_close_all_menus)
	
	#连接设置功能信号
	$SettingsPanel/FullscreenRow/Btn_Fullscreen.toggled.connect(_on_fullscreen_toggled)
	$SettingsPanel/VolumeSlider.value_changed.connect(_on_volume_changed)
	$SettingsPanel/Btn_Exit.pressed.connect(_on_exit_game)
	
	#初始化设置面板的状态
	#初始化音量滑条位置
	volume_slider.min_value = 0.0
	volume_slider.max_value = 1.0
	volume_slider.step = 0.05 #每次拖动的步长
	var current_db = AudioServer.get_bus_volume_db(master_bus_index)
	volume_slider.value = db_to_linear(current_db)
	$SettingsPanel/VolumeSlider.value = db_to_linear(AudioServer.get_bus_volume_db(master_bus_index))
	#初始化全屏按钮状态
	var is_currently_fullscreen = (DisplayServer.window_get_mode() == DisplayServer.WINDOW_MODE_FULLSCREEN)
	$SettingsPanel/FullscreenRow/Btn_Fullscreen.button_pressed = (DisplayServer.window_get_mode() == DisplayServer.WINDOW_MODE_FULLSCREEN)
	#初始隐藏面板
	settings_panel.hide()
	save_load_panel.hide()
	
	#初始化酒单
	pos_hidden_x = get_viewport().get_visible_rect().size.x
	pos_closed = drink_menu_system.position
	#手机完全滑出后的位置 = 屏幕宽 - 手机宽
	pos_shown_x = pos_hidden_x - drink_menu_system.size.x
	pos_opened = pos_closed + open_offset
	
	drink_menu_system.position = pos_closed
	
	#初始手机在外面，Handle按钮在里面显示
	drink_menu_system.position.x = pos_hidden_x
	if start_hidden:
		btn_handle.visible = false
	else:
		btn_handle.visible = true
	
	#连接信号
	Dialogic.signal_event.connect(_on_dialogic_signal)
	btn_handle.pressed.connect(_open_phone)
	btn_close.pressed.connect(_close_phone)
	btn_left.pressed.connect(_on_prev_page)
	btn_right.pressed.connect(_on_next_page)
	
	

func _on_dialogic_signal(argument: String):
	#在timeline里，如果遇到Signal事件参数是"unlock_drink_menu"
	if argument == "unlock_drink_menu":
		unlock_and_show_drink_menu()
		
	#如果遇到"hide_drink_menu"(比如进入剧情不想让玩家乱点)
	elif argument == "hide_drink_menu":
		force_hide_drink_menu()

func unlock_and_show_drink_menu():
	#修改 Dialogic 变量
	Dialogic.VAR.HUD.drink_menu_unlocked = true
	
	#显示按钮
	btn_handle.visible = true
	print("酒单功能已解锁！")

#功能函数：强制隐藏(用于主菜单或特殊剧情)
func force_hide_drink_menu():
	btn_handle.visible = false

#功能函数：根据解锁状态刷新(用于切换场景时)
func update_drink_menu_visibility():
	#只有当变量为true 时，才显示按钮
	var is_unlocked = Dialogic.VAR.get_variable("HUD.drink_menu_unlocked", false)
	if is_unlocked:
		btn_handle.visible = true
	else:
		btn_handle.visible = false

func _open_phone():
	if sfx_phone_open.stream:
		#加一点随机音调，让声音听起来不那么死板
		sfx_phone_open.pitch_scale = randf_range(0.95, 1.05)
		sfx_phone_open.play()

	#隐藏呼出按钮
	btn_handle.visible = false
	buttons_container.visible = true
	menu_content.visible = true
	#初始化手机屏幕 (显示第一页)
	current_page = 0
	_update_page_display()
	
	#播放滑入动画
	if menu_tween: menu_tween.kill()
	menu_tween = create_tween().set_trans(Tween.TRANS_BACK).set_ease(Tween.EASE_OUT)
	#使用Vector2的position属性
	menu_tween.tween_property(drink_menu_system, "position", pos_opened, anim_duration)

func _close_phone():
	if sfx_phone_close.stream:
		sfx_phone_close.pitch_scale = randf_range(0.95, 1.05)
		sfx_phone_close.play()
	
	buttons_container.visible = false
	menu_content.visible = false #屏幕变回锁屏/黑屏状态
	
	#等待一小会儿
	await get_tree().create_timer(0.15).timeout
	
	#播放滑出动画
	if menu_tween: menu_tween.kill()
	menu_tween = create_tween().set_trans(Tween.TRANS_CUBIC).set_ease(Tween.EASE_IN)
	menu_tween.tween_property(drink_menu_system, "position", pos_closed, 0.5)
	
	#动画结束后，显示呼出按钮
	await menu_tween.finished
	btn_handle.visible = true


func _on_prev_page():
	if current_page > 0:
		current_page -= 1
		_update_page_display()

func _on_next_page():
	if current_page < menu_pages.size() - 1:
		current_page += 1
		_update_page_display()

#刷新页面显示 按钮状态
func _update_page_display():
	#换图
	var tex = load(menu_pages[current_page])
	menu_content.texture = tex
	
	#处理按钮状态(变灰/禁用)
	#如果是第一页，禁用左键
	btn_left.disabled = (current_page == 0)
	#如果是最后一页，禁用右键
	btn_right.disabled = (current_page == menu_pages.size() - 1)
	
	#视觉上的变灰(利用 modulate)
	#如果被禁用了，颜色变暗；否则变回白色(原色)
	btn_left.modulate = Color(0.5, 0.5, 0.5) if btn_left.disabled else Color.WHITE
	btn_right.modulate = Color(0.5, 0.5, 0.5) if btn_right.disabled else Color.WHITE

func _close_all_menus():
	settings_panel.hide()
	save_load_panel.hide()
	#恢复游戏运行
	get_tree().paused = false
#全屏切换
func _on_fullscreen_toggled(is_fullscreen: bool):
	if is_fullscreen:
		DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_FULLSCREEN)
	else:
		DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_WINDOWED)

#音量调节
func _on_volume_changed(value: float):
	AudioServer.set_bus_volume_db(master_bus_index, linear_to_db(value))

#退出游戏
func _on_exit_game():
	get_tree().quit()

func _on_open_settings():
	_close_all_menus() #先关掉其他的
	settings_panel.show()
	get_tree().paused = true #暂停游戏
	
#打开存读档面板
func _on_open_save_load(save_mode: bool):
	
	_close_all_menus()
	is_save_mode = save_mode
	save_load_panel.show()
	get_tree().paused = true
	
	#更新标题
	if is_save_mode:
		title_label.text = "选择存档位置"
	else:
		title_label.text = "选择读取档案"
	
	#刷新列表
	_refresh_slots()

#刷新存档槽位列表
const SLOT_BUTTON_SCENE = preload("res://scene/SlotButton.tscn") 

func _refresh_slots():
	print("--- 开始刷新列表 ---")

	#清空旧按钮
	for child in slot_list_container.get_children():
		child.queue_free()
	
	for i in range(1, 11):
		var slot_name = "Slot_" + str(i)
		var btn = SLOT_BUTTON_SCENE.instantiate()
		btn.set_meta("no_click_sound", true)
		#尝试获取节点
		var label_id = btn.get_node_or_null("%Label_ID")
		var label_info = btn.get_node_or_null("%Label_Info")
		

		#if label_id == null:
			#print("错误：找不到 %Label_ID，请检查 SlotButton.tscn 里是否勾选了'唯一名称'")
		#if label_info == null:
			#print("错误：找不到 %Label_Info，请检查 SlotButton.tscn 里是否勾选了'唯一名称'")

		#设置编号
		if label_id: label_id.text = "NO.%02d" % i

		#检查 Dialogic 是否认为有存档
		if Dialogic.Save.has_slot(slot_name):
			print("发现存档：" + slot_name)
			var info = Dialogic.Save.get_slot_info(slot_name)
			var date = info.get("date", "----/--/--")
			var time = info.get("time", "--:--")
			
			#打印设置的文字
			var show_text = "%s %s" % [date, time]
			print("准备设置文字为: " + show_text)
			
			if label_info:
				if is_save_mode:
					label_info.text = "覆盖存档 %s %s" % [date, time]
				else:
					label_info.text = "%s %s" % [date, time]
			#尝试获取在 extra_data 里存的路径
			var custom_thumb_path = info.get("thumbnail_path", "")
			
			#获取 TextureRect 节点
			var thumb_rect = btn.get_node_or_null("%Thumbnail")
			
			if thumb_rect and custom_thumb_path != "":
				#检查文件是否存在
				if FileAccess.file_exists(custom_thumb_path):
					var img = Image.load_from_file(custom_thumb_path)
					var tex = ImageTexture.create_from_image(img)
					thumb_rect.texture = tex
				else:
					print("图片文件丢失: " + custom_thumb_path)

		else:
			# print("空槽位：" + slot_name)
			if label_info: label_info.text = "---- 空 ----"

		#连接信号并添加
		btn.pressed.connect(func(): _on_slot_clicked(slot_name))
		slot_list_container.add_child(btn)
	
	print("--- 刷新结束 ---")
#点击槽位后的逻辑
func _on_slot_clicked(slot_name: String):
	print("点击了槽位: ", slot_name)
	
	if is_save_mode:
		#如果是存档模式，播存档音效
		if sfx_save and sfx_save.stream:
			sfx_save.play()
	else:
		#如果是读档模式，播读档音效
		if sfx_load and sfx_load.stream:
			sfx_load.play()
			
	if is_save_mode:
		var current_scene_path = get_tree().current_scene.scene_file_path
		Dialogic.VAR.set_variable("saved_scene_path", current_scene_path)
		
		var current_root = get_tree().current_scene
		
		if current_root and "current_customer_data" in current_root:
			var data = current_root.current_customer_data
			if data:
				Dialogic.VAR.set_variable("current_customer_id", data.resource_path)
		
		#手动截图 (保持不变)
		self.visible = false
		await get_tree().process_frame
		await get_tree().process_frame
		var image = get_viewport().get_texture().get_image()
		var thumb_width = 288
		var thumb_height = int(thumb_width * image.get_height() / image.get_width())
		image.resize(thumb_width, thumb_height)
		
		var dir = DirAccess.open("user://")
		if not dir.dir_exists("screenshots"): dir.make_dir("screenshots")
		var img_path = "user://screenshots/%s.png" % slot_name
		image.save_png(img_path)
		
		#构造时间数据 (保持不变)
		var time_dict = Time.get_datetime_dict_from_system()
		var date_str = "%d/%02d/%02d" % [time_dict.year, time_dict.month, time_dict.day]
		var time_str = "%02d:%02d" % [time_dict.hour, time_dict.minute]
		var extra_data = {
			"date": date_str, 
			"time": time_str, 
			"thumbnail_path": img_path
		}
		
		self.visible = true
		
		#执行存档
		Dialogic.Save.save(slot_name, false, 0, extra_data)
		print("存档成功: %s -> %s" % [slot_name, current_scene_path])
		
		await get_tree().process_frame
		_refresh_slots()

	else:
		print("正在读取: " + slot_name)
		var slot_info = Dialogic.Save.get_slot_info(slot_name)
		#加载数据
		Dialogic.Save.load(slot_name)
		update_drink_menu_visibility()
		#获取我们要去哪里
		var target_scene = Dialogic.VAR.get_variable("saved_scene_path")
		
		#判断并跳转
		if target_scene != null and target_scene != "":
			print("目标场景: ", target_scene)
			
			get_tree().change_scene_to_file(target_scene)
		else:
			VN_SystemUI.pending_load_slot = slot_name
			# 可以在这里写一个默认回退，比如回到主菜单或第一关
			get_tree().change_scene_to_file("res://scene/start_.tscn")
		
		if is_inside_tree(): get_tree().paused = false
		#恢复 UI
		update_drink_menu_visibility()
		_close_all_menus()
		
#控制 HUD 显示/隐藏的函数
func show_hud():
	if has_node("HUD"):
		$HUD.visible = true

func hide_hud():
	if has_node("HUD"):
		$HUD.visible = false

#在主菜单打开设置
func open_only_settings():
	#确保 HUD是隐藏的
	hide_hud()
	#打开设置面板
	_on_open_settings()
